package com.jiangyg.devtools.ui;

import com.intellij.ui.JBCardLayout;
import com.intellij.ui.components.JBPanel;
import com.jiangyg.devtools.toolkit.Assert;

import java.awt.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

/**
 * 类描述：多任务阶段面板
 *
 * @author jiangyg
 * @date 2023-08-14
 */
public class MultiTaskPanel extends JBPanel<MultiTaskPanel> {

    private Consumer<String> listener;

    private final JBCardLayout layout = new JBCardLayout();

    private final java.util.List<String> steps = new ArrayList<>();

    private final Map<String, Component> componentMap = new HashMap<>();

    public MultiTaskPanel() {
        super();
        this.setLayout(layout);
    }

    /**
     * 功能描述：追加任务组件
     *
     * @param name      任务名
     * @param component 任务组件
     */
    public void addTaskComponent(String name, Component component) {
        if (componentMap.containsKey(name)) {
            return;
        }
        this.add(name, component);
        componentMap.put(name, component);
    }

    /**
     * 功能描述：是否包含任务组件
     *
     * @param name 任务名
     * @return 是否
     */
    public boolean containsTaskComponent(String name) {
        return componentMap.containsKey(name);
    }

    /**
     * 功能描述：获取任务组件
     *
     * @param name 任务名
     * @return 任务组件
     */
    public <T> T getTaskComponent(String name) {
        return (T) componentMap.get(name);
    }

    /**
     * 功能描述：显示指定任务面板
     *
     * @param name 任务名
     */
    public void showTask(String name) {
        steps.add(name);
        showPanelByName(name);
    }

    /**
     * 功能描述：显示上一个任务
     */
    public void showPreviousTask() {
        Assert.notEmpty(steps);

        int index;
        if ((index = steps.size() - 1) >= 0) {
            steps.remove(index);
        }

        if ((index = steps.size() - 1) >= 0) {
            showPanelByName(steps.get(index));
        }
    }

    private void showPanelByName(String step) {
        layout.show(this, step);
        doListenerEvent(step);
    }

    public void setListener(Consumer<String> listener) {
        this.listener = listener;
    }

    private void doListenerEvent(String step) {
        if (listener != null) {
            listener.accept(step);
        }
    }

}
